/*
 * Copyright 2010
 * Jairou Software Organization
 * All Rights Reserved.
 * 
 * This software is the proprietary 
 * information of Roger Ramia
 * and the Jairou Software Organization 
 * Use is subject to license terms.
 * 
 * For licensing information please visit
 * http://www.jairou.org/license
 * 
 * @author Roger Ramia
 */
package org.jairou.web;

import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jairou.core.Exceptions;
import org.jairou.util.JSON;

public class JSONServlet
extends HttpServlet {
	
	/**
	 * serial version id
	 */
	private static final long serialVersionUID = -8419183542219790382L;
	
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) 
	throws ServletException {
		this.doPost(req, resp);
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) 
	throws ServletException {
		try {
			if (Web.isDefined(req)) {
				Writer out = resp.getWriter();
				Map result = new HashMap();
				Object ctx = Web.getContext(req);
				try {
					if (!Exceptions.hasErrors(ctx)) {
						Object client = Web.getScope(Web.CLIENT_SCOPE_KEY, ctx);
						if (client != null) {
							if (client instanceof Map) result.putAll((Map)client);
							else result.put("result", client);
						}
						result.put("success", true);
					}
					else throw new Exception("The request contains errors.");
				}
				catch (Throwable t) {
					result.put("errors", Exceptions.getErrors(ctx));
					result.put("success", false);
					t.printStackTrace();
				}	
				finally {			
					if (out != null) {
						//resp.setContentType("application/json");
						resp.setContentType("text/html");
						JSON.encode(result, out);
						out.flush();
						out.close();
					}
				}
			}
			else resp.sendError(404);
		}
		catch(Exception e) {
			throw new ServletException(e);
		}
	}
}